package com.jeedroid.weibo.oauth;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.util.Log;

import com.jeedroid.weibo.assist.Base64;
import com.jeedroid.weibo.assist.HMAC_SHA1;
import com.jeedroid.weibo.assist.QParameter;
public class OAuth
{
	public static final String CONSUMER_KEY = "801065856";
	public static final String CONSUMER_SECRET = "2d438b43515d2040f4c664cd28b25b36";
	public static final String SIGNATURE_METHOD = "HMAC-SHA1";
	public static final String ENCODING = "UTF-8";
	
	//生成时间戳
	private static String generateTimestamp()
	{
		return String.valueOf(System.currentTimeMillis()/1000);
	}
	
	//单次值 防止重放攻击
	private static String generateNonce()
	{
		String str="abcdefghijklmnopqrstuvwxyz0123456789";
		StringBuilder builder=new StringBuilder();
		Random random=new Random();
		for(int i=0;i<32;i++)
		{
			int m=random.nextInt(36);
			builder.append(str.charAt(m));
		}
		return builder.toString();
	}
	
	//对url进行编码
	private static String encode(String url)
	{
		if(url==null||url.equals(""))
			return "";
		String encoded="";
		try
		{
			encoded=URLEncoder.encode(url,"UTF-8");
		} catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		StringBuilder sBuilder=new StringBuilder();
		for (int i = 0; i < encoded.length(); i++)
		{
			char c = encoded.charAt(i);
			if (c == '+')
			{
				sBuilder.append("%20");
			} else if (c == '*')
			{
				sBuilder.append("%2A");
			}
			// URLEncoder.encode()会把“~”使用“%7E”表示，因此在这里我们需要变成“~”
			else if ((c == '%') && ((i + 1) < encoded.length()) && ((i + 2) < encoded.length()) & (encoded.charAt(i + 1) == '7') && (encoded.charAt(i + 2) == 'E'))
			{
				sBuilder.append("~");
				i += 2;
			} else
			{
				sBuilder.append(c);
			}
		}
		return sBuilder.toString();
	}
	
	//生成Signature Base String
	private static String generateBaseString(String httpMethod,String url,List<QParameter> params)
	{
		StringBuilder stringBuilder=new StringBuilder();
		stringBuilder.append(httpMethod.toUpperCase()+"&");
		url=encode(url.toLowerCase());
		stringBuilder.append(url+"&");
		Collections.sort(params);
		for(QParameter parameter:params)
		{
			stringBuilder.append(parameter.getName());
			stringBuilder.append("%3D");
			stringBuilder.append(parameter.getValue());
			stringBuilder.append("%26");
		}
		stringBuilder.delete(stringBuilder.length()-3, stringBuilder.length());
		return stringBuilder.toString();
	}
	
	private static String generateSignature(String httpMethod,String url,List<QParameter> params,String consumerSecret,String tokenSecret) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException
	{
		String baseString =generateBaseString(httpMethod,url,params);
		//构造密钥
		String secret="";
		if(null==tokenSecret||tokenSecret.equals(""))
		{
			secret=encode(consumerSecret)+"&";
		}
		else
		{
			secret=encode(consumerSecret)+"&"+encode(tokenSecret);
		}
		//生成签名值
		byte[] encryptBytes = HMAC_SHA1.HmacSHA1Encrypt(baseString, secret);
		return Base64.encode(encryptBytes);
	}
	
	//获取请求参数
	private static String generateRequestParams(String httpMethod,String url,String tokenSecret) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException
	{
		List<QParameter> params=new ArrayList<QParameter>();
		params.add(new QParameter("oauth_consumer_key",CONSUMER_KEY));
		params.add(new QParameter("oauth_signature_method",SIGNATURE_METHOD));
		params.add(new QParameter("oauth_timestamp",generateTimestamp()));
		params.add(new QParameter("oauth_nonce",generateNonce()));
		params.add(new QParameter("oauth_callback","null"));
		params.add(new QParameter("oauth_version","1.0"));
		//获取签名值
		String signature=generateSignature(httpMethod,url,params,CONSUMER_SECRET,tokenSecret);
		params.add(new QParameter("oauth_signature",signature));
		Collections.sort(params);
		StringBuilder requestUrlParams=new StringBuilder();
		for(QParameter parameter:params)
		{
			requestUrlParams.append(parameter.getName());
			requestUrlParams.append("=");
			requestUrlParams.append(parameter.getValue());
			requestUrlParams.append("&");
		}
		requestUrlParams.delete(requestUrlParams.length()-1, requestUrlParams.length());
		return requestUrlParams.toString();
	}
	
	
	//获取未授权的request_token
	public static String getNotRequestToken() throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException
	{
		SyncHttp ht=new SyncHttp();
		return ht.httpGet("https://open.t.qq.com/cgi-bin/request_token", generateRequestParams("get","https://open.t.qq.com/cgi-bin/request_token",""));
	}
	
	//将请求未授权的request_token时返回的三个参数读取出来(oauth_token=8ea788a986d24617a937b78f82bd312e&oauth_token_secret=fa6af3632a75f6cfe1833f58ca21a126&oauth_callback_confirmed=true)
	public static Map<String,String> getOauthToken(String responseParams)
	{
		Map<String,String> map=new HashMap<String,String>();
		if(responseParams!=null&&!responseParams.equals(""))
		{
			String[] responseData = responseParams.split("&");
			if(responseData.length>2)
			{
				String oauth_token_prop=responseData[0];
				String oauth_token_secret=responseData[1];
				String []token=oauth_token_prop.split("=");
				if(token.length==2)
				{//oauth_token的值
					map.put("oauth_token", token[1]);
				}
				String []secret=oauth_token_secret.split("=");
				if(secret.length==2)
				{//oauth_token_secret的值
					map.put("oauth_token_secret", secret[1]);
				}
			}
		}
		return map;
	}
	
	//获取用户授权的request_token
	public static String getYesRequestToken()
	{
		String url="https://open.t.qq.com/cgi-bin/authorize";
		String notRequestToken;
		try
		{
			notRequestToken = getNotRequestToken();
			Map<String,String> map=getOauthToken(notRequestToken);
			String oauth_token=map.get("oauth_token");
			String params="oauth_token="+oauth_token;
			SyncHttp ht=new SyncHttp();
			String yesRequestToken=ht.httpGet(url, params);
			return yesRequestToken;
		} catch (InvalidKeyException e)
		{
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return null;
		
	}
}
